package com.achen.controller;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author achen
 * @create 2020-04-27 22:09
 */
@Controller
public class KaptchaController {
    @Autowired
    private Producer producer;

    @RequestMapping("/kaptcha")
    public void getKaptcha(HttpSession session, HttpServletResponse response){
        String text = producer.createText();
        System.out.println(text);
        session.setAttribute("kaptcha",text);
        //生成验证码图片
        BufferedImage image = producer.createImage(text);
        //把图片以流的方式响应给客户端，图片以jpg的格式写入到响应的输出流
        try {
            ImageIO.write(image,"jpg",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
